Product:    ISaGRAF 4.0x
Date: 29-January-2001
File: String to Real.htm
Subject: How to convert a String to a Real
Keywords: String - Real - conversion

____________________________________________________________________

The ANY_TO_REAL conversion does not work with string inputs.

To work-around that you can

develop a C function and add it to the virtual machine if your system supports this conversion

or

Use the following IEC function block.

Parameters are as follows:

Name

Type Direction Comment

StrInput

STRING(255) Input -

RealOutput

REAL Output -

Status

BOOL Output FALSE if Input String cannot be converted

Zero

BOOL Local True if there is a '0' at the begining of the string

Minus

BOOL Local True if there is a '-' at the begining of the string

TempString1

STRING(255) Local -

TempString2

STRING(255) Local -

TempReal1

REAL Local -

TempReal2

REAL Local -

TempReal3

REAL Local -

StrLength

DINT Local Length of the Input string

Index

DINT Local -

Code

Ascii code Local -

OneChar

STRING(2) Local -

Status := TRUE; (* the string can be converted to a real *)
StrLength := MLEN(StrInput);
If (StrLength = 0) then (* empty string *)
    Status := FALSE;
end_if;
Index := 0;
While (Index < StrLength AND Status = TRUE) Do
    Index := Index + 1;
    Code := ASCII(StrInput, Index);
    if (Code <> 45 AND          (* '-' *)
    Code <> 46) Then (* '.' *)
        If (Code < 48 OR Code > 58) Then (* not between '0' and '9' *)
            Status := FALSE;
        End_If;
    End_If;
End_While;

if (Status) then
    TempString1 := replace(StrInput , '', 1, find(StrInput , '.'));
    Zero := TRUE;
    Minus := FALSE;
    TempString2 := TempString1;
    While (Zero) Do
        OneChar := Left(TempString2,1);
        if (OneChar = '0') then
            TempString2 := Delete(TempString2,1,1); (* delete the '0' *)
        elsif (OneChar = '-') then
            Minus := TRUE;
            TempString2 := Delete(TempString2,1,1); (* delete the '-' *)
        else
            Zero := FALSE; (* first non Zero character *)
        end_if;
    End_While;
    If (Minus) then
        TempString2 := Insert(TempString2,'-',1); (* put back the '-' *)
    End_if;

    TempReal1 := expt(10.0, (mlen(StrInput )-find(StrInput ,'.')));
    TempReal2 := trunc(TempReal1);

    TempReal3 := ANY_TO_REAL(TempString2);

    RealOutput := TempReal3 / TempReal2;
Else
    RealOutput := 0.0;
End_If;

____________________________________________________________________

Copyright © 1999-2009 ICS Triplex ISaGRAF Inc. All rights reserved.